package com.tiantian.quanminxiu.fragment;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.adapter.BannerVPAdatper;
import com.tiantian.quanminxiu.adapter.HallListAdapter;
import com.tiantian.quanminxiu.model.RoomInfo;
import com.tiantian.quanminxiu.presenter.MainHallPresent;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.FragmentBase;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.view.MainHallView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

/*
* 首页
* */
public class Fragment_Main_Hall extends FragmentBase implements MainHallView, BaseQuickAdapter.RequestLoadMoreListener{

    private MainHallPresent present;
    // 查询分页用到的参数
    private boolean boolPageLoading = false;            // 是否正在加载，防止重复加载
    private boolean boolPageEnd = false;                // 所有数据已加载完成
    private boolean P_Get = true;                       // 是否重新获取分页信息
    private int P_Current = 0;                          // 当前页数
    private int P_Total = 0;                            // 记录总条数
    private int P_MaxCode = 0;                          // MaxCode
    private int iDisplayLength = 14;                    // 数量（分页数量）

    private AutoScrollViewPager vpHallBanner;
    private RecyclerView mRecyclerView;
    private LinearLayout linPointsGift;
    private HallListAdapter hallAdapter;

    private View Header;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_hall, container, false);

        Init(view);
        InitView(view);

        present = new MainHallPresent();
        present.attachView(this);

        mSwipeRefresh.setOnRefreshListener(() -> {
            UserData.Reload.Fragment_Hall = true;
            if(hallAdapter!=null){
                hallAdapter.openLoadMore(iDisplayLength);
                hallAdapter.removeAllFooterView();
            }
            PageInit();
        });
        UserData.Reload.Fragment_Hall = true;
        return view;
    }
    //endregion

    public void InitView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(thisContext,2);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        Header = View.inflate(thisContext, R.layout.main_hall_header, null);
        vpHallBanner = (AutoScrollViewPager) Header.findViewById(R.id.vpHallBanner);
        linPointsGift = (LinearLayout) Header.findViewById(R.id.linPointsGift);

        hallAdapter = new HallListAdapter(thisActivity);
        hallAdapter.openLoadAnimation();
        hallAdapter.openLoadMore(iDisplayLength);
        View customLoading = thisActivity.getLayoutInflater().inflate(R.layout.recycleview_loading, (ViewGroup) mRecyclerView.getParent(), false);
        hallAdapter.setLoadingView(customLoading);
        mRecyclerView.setAdapter(hallAdapter);
        hallAdapter.addHeaderView(Header);
    }


    //region PageInit()
    private void PageInit() {
        if (!UserData.Reload.Fragment_Hall) {
            return;
        }
        UserData.Reload.Fragment_Hall = false;
        //////////////////////////首页信息////////////////////////////
        hallAdapter.getData().clear();
        hallAdapter.setOnLoadMoreListener(this);
        P_Get = true;
        P_Current = 0;
        P_Total = 0;
        P_MaxCode = 0;
        boolPageEnd = false;
        present.initBanner();
        // 读取数据
        PageData();
    }
    //endregion

    private void PageData(){
        if(!boolPageLoading){
            boolPageLoading = true;
            present.initHall(P_Total,P_Current*iDisplayLength,iDisplayLength);
        }
    }

    @Override
    public void getData(JSONArray jsonArray, int iDisplayStart,int P_Total) {
        P_Current++;
        this.P_Total = P_Total;
        List<RoomInfo> list = new ArrayList<RoomInfo>();
       for (int i=0;i<jsonArray.length();i++){
            JSONObject obj = jsonArray.optJSONObject(i);
           RoomInfo info = new RoomInfo();
           int User_ID = obj.optInt("User_ID");
           info.setRoomId(User_ID);
           info.setIsPlaying(obj.optInt("Live"));
           info.setIsMobile(obj.optInt("Live_IsMobile"));
           info.setImgUrl(APPUtils.createUserCover(User_ID));
           info.setAnchorName(obj.optString("NickName"));
           info.setAnchorid(User_ID);
           info.setHeat(obj.optInt("HotValue"));
           info.setTitle(obj.optString("RoomTitle"));
           if (info.getIsPlaying()==1){
               info.setLive_Mode(obj.optInt("Live_Mode"));
           }
           list.add(info);
        }
        if (jsonArray.length()<iDisplayLength)
        {
            hallAdapter.setOnLoadMoreListener(null);
        }
        hallAdapter.addData(list);
        hallAdapter.notifyDataSetChanged();
        boolPageLoading = false;
    }

    @Override
    public void initBanner(JSONArray array) {
        linPointsGift.removeAllViews();
        List<ImageView> imageViews = new ArrayList<ImageView>();
        for (int i = 0; i < array.length(); i++) {
            ImageView imageView = new ImageView(
                    thisContext);
            APPUtils.displayImage(array.optJSONObject(i).optString("Image"), imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setTag(array.optJSONObject(i).optString("Url"));
            imageViews.add(imageView);
        }
        BannerVPAdatper adatper = new BannerVPAdatper(thisActivity,
                imageViews, linPointsGift,vpHallBanner);
        vpHallBanner.setAdapter(adatper);
        vpHallBanner.setOnPageChangeListener(adatper);
    }

    @Override
    public void onResume() {
        super.onResume();
        PageInit();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        present.detachView();
    }

    @Override
    public void onLoadMoreRequested() {
        PageData();
    }
}